<?php

include_once( '../api/session.php' );

require_once( '../api/Client.class.php' );

include_once( '../library/config.php' );
include_once( APPLICATION.'User.class.php' );
include_once( APPLICATION.'Payment.class.php' );
include_once( APPLICATION.'Paymentrequest.class.php' );

$pname = 'JaPagoJo';

if( isset( $_POST['username'] )) {
  $response = Client::login( $_POST['username'], $_POST['password'] );
  if( strtolower( $response['status'] )  == 'ok' ) {
    $_SESSION['token'] = $response['token'];
    $c = new Client( $response['token'] );
    $profile = $c->getProfile();
            
    include_once( 'templates/header.tmp.php' );
 
      $acctlist = $c->getAccounts();
      if( $profile['data']['accounts'] ) {
        foreach( $profile['data']['accounts'] as $acct ) {
          $accounts[] = $c->getAccountDetail( $acct );
        }
      }
        
      //print_r( $accounts );
      include_once( 'templates/pay_client.tmp.php' );

  }
  else
    //login failed
    echo 'FAIL!';
} elseif ($_SESSION['token'] ) {
	$c = new Client( $_SESSION['token'] );
  $profile = $c->getProfile();
	
  include_once( 'templates/header.tmp.php' );
  
	if( !isset( $_POST['accountchoice'] ) ) {
 
      $acctlist = $c->getAccounts();
      if( $profile['data']['accounts'] ) {
        foreach( $profile['data']['accounts'] as $acct ) {
          $accounts[] = $c->getAccountDetail( $acct );
        }
      }
        
      //print_r( $accounts );
      include_once( 'templates/pay_client.tmp.php' );
	} else {
		$data['originAccount'] = $_POST['accountchoice'];
		$pay = new Payment( $_POST['idp'] );
		$us = new User( $pay->getId_user() );
		$desin = $c->getAccountDetail( $us->getId_account() );
		$data['destinationAccount'] = $desin['data']['accountNumber'];
		$prr = Paymentrequest::findByEmailAndIdPayment( $_POST['email'], $_POST['idp'] );
		$data['value'] = $prr[0]->getAmount();
		$data['additionalData']['concept'] = $pay->getSubject();
		$data['additionalData']['payee'] = $prr[0]->getName();
		
		$prr[0]->setPaid( 1 );
		//$prr[0]->update();
		
		$ret = $c->transfer( $data );
		
		if( strtolower( $ret['status'] ) == 'ok' )
		  include_once( 'templates/pay_noclient2.tmp.php' );
	}
}
include_once( 'templates/footer.tmp.php' );

?>